package com.amorcloud.pig.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.amorcloud.pig.MyApp;
import com.amorcloud.pig.R;
import com.amorcloud.pig.bean.UserInfoBean;
import com.amorcloud.pig.utils.UserDaoUtils;

import org.w3c.dom.Text;

import java.util.List;

public class SigninActivity extends BaseActivity implements View.OnClickListener {

    Button signin;
    EditText mUserName, mPassword;
    CheckBox mIsAdmin;

    @Override
    protected void init() {
        setContentView(R.layout.activity_sigin);
        initView();
    }

    private void initView() {
        signin = findViewById(R.id.btn_signin);
        signin.setOnClickListener(this);

        mUserName = findViewById(R.id.etv_username);
        mPassword = findViewById(R.id.etv_password);
        mIsAdmin = findViewById(R.id.cb_isadmin);
        mIsAdmin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_signin:
                verifyUser();
                break;
            case R.id.cb_isadmin:
                if(mIsAdmin.isChecked()) {
                    mUserName.setText("admin");
                } else {
                    mUserName.setText("");
                }
                break;
            default:
                break;
        }
    }

    private void verifyUser() {
        String username = mUserName.getText().toString();
        String password = mPassword.getText().toString();
        if(TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            Toast.makeText(this,"账号或密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        boolean isAdmin = mIsAdmin.isChecked();
        List<UserInfoBean> list;
        if(isAdmin) {
            list = UserDaoUtils.queryWhere("where USER_NAME=? and PASSWROD=? and IS_ADMIN=1", username, password);
            if(list != null && list.size() == 1) {
                MyApp.currentUser = list.get(0);
                startActivity(new Intent(this, MainActivity.class));
                this.finish();
            } else {
                Toast.makeText(this,"账号或密码错误", Toast.LENGTH_SHORT).show();
            }
        } else {
            list = UserDaoUtils.queryWhere("where USER_NAME=? and PASSWROD=? and IS_ADMIN=0", username, password);
            if(list != null && list.size() >= 1) {
                MyApp.currentUser = list.get(0);
                startActivity(new Intent(this, MainActivity.class));
                this.finish();
            } else {
                Toast.makeText(this,"账号或密码错误", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
